<?php
class ArticlesController extends AppController {

    public $uses = array('Article','Rating');
    public $helpers = array('Rss','Ajax','ArticleMenu','Time','Pagination','Rating');
    private $created = null;

    public function beforeFilter() {
        parent::beforeFilter();
        @$this->created = '%'.$this->params['year'] . '-' . $this->params['month'] . '-' . $this->params['day'] . '%';
    }

    public function admin_index() {
        $this->Article->recursive = 0;
        $this -> paginate = array('order' => 'Article.created desc');
        $this->set('articles', $this->paginate());
    }

    public function admin_add() {
        if (!empty($this->data)) {
            $this->Article->create();
            if ($this->Article->save($this->data)) {
                $this->Session->setFlash(__('The Article has been saved',true));
                $this->redirect(array('action'=>'index'), null, true);
            } else {
                $this->Session->setFlash(__('The Article could not be saved. Please, try again.',true));
            }
        }
        $this->get_article_data();
    }

    public function admin_edit($id = null) {
        if (!$this->Article->findById($id)) {
            $this->Session->setFlash(__('Invalid article',true));
            $this->redirect(array('action'=>'index'), null, true);
        }
        if (!empty($this->data)) {
            if ($this->Article->save($this->data)) {
                $this->Session->setFlash(__('The Article has been saved',true));
                $this->redirect(array('action'=>'index'), null, true);
            } else {
                $this->Session->setFlash(__('The Article could not be saved. Please, try again.',true));
            }
        } else {
            $this->data = $this->Article->findById($id);
        }
        $this->get_article_data();
    }

    public function admin_delete($id = null) {
        if (!$this->Article->findById($id)) {
            $this->Session->setFlash(__('Invalid article',true));
            $this->redirect(array('action'=>'index'), null, true);
        }
        if ($this->Article->del($id)) {
            $this->Session->setFlash(__('Article deleted',true));
        } else {
            $this->Session->setFlash(__('The Article could not be deleted. Please, try again.',true));
        }
        $this->redirect(array('action'=>'index'), null, true);
    }

    public function admin_delete_articles() {
        if($this->Article->deleteAll(array('Article.id'=>$this->data['ArticlesDelete']))) {
            $this->Session->setFlash(__('Articles deleted',true));
        } else {
            $this->Session->setFlash(__('The Articles could not be deleted. Please, try again.',true));
        }
        $this->redirect(array('action'=>'index'), null, true);
    }

    public function admin_preview() {
        $this->set("preview",$this->data['Article']);
    }

    public function rss() {
        $this->set('articles',$this->Article->findAll(array('Article.visible=1','Article.created < now()'),null,array('Article.created'=>'desc')));
    }

    public function index() {
        $this->Article->recursive = 1;
        $this->paginate = array('limit'=>Configure::read('Homepage.articles'),'order' => 'Article.created desc','conditions'=>array('show_on_index'=>1,'visible'=>1,'Article.created<=now()'));
        $this->set('articles', $this->paginate());
    }

    public function view($seo_link = null) {
        $this->Article->update_visited($seo_link,$this->created);
        $article = $this->Article->find_by_seo_and_date($seo_link,$this->created);
        $url = $this->params['year'].'/'.$this->params['month'].'/'.$this->params['day'].'/'.$seo_link;
        $recentArticles = $this->Article->recent($article['Article']['category_id']);
        $this->set(compact("article","url","recentArticles"));
    }

    public function comment_add($seo_link = null) {
        if(!$this->Article->find_by_seo_and_date($seo_link,$this->created)) {
            $this->Session->setFlash(__('Invalid article',true));
            $this->redirect(array('action'=>'index'), null, true);
        }
        if (!empty($this->data)) {
            $this->Article->Comment->create();
            if ($this->Article->Comment->save($this->data)) {
                if(!$this->RequestHandler->isAjax()) {
                    $this->Session->setFlash(__('Comment saved',true));
                    $url = $this->params['year'].'/'.$this->params['month'].'/'.$this->params['day'].'/'.$seo_link.'/#comment_'.$this->Article->Comment->getInsertId();
                    $this->redirect(array('action'=>$url),null,true);
                } else {
                    $this->set("comment",$this->Article->Comment->findById($this->Article->Comment->getInsertId()));
                    $this->action = "comment_action";
                }
            } else {
                $this->Session->setFlash(__('The Comment could not be saved. Please, try again.',true));
            }
            $this->set('url',$this->params['year'].'/'.$this->params['month'].'/'.$this->params['day'].'/'.$seo_link);
        }
    }

    public function rating($seo_link,$rating) {
        $id = $this->Article->find_by_seo_and_date($seo_link,$this->created);
        $id = $id['Article']['id'];

        $data = array('article_id'=>$id,'value'=>$rating,'ip_address'=>$this->RequestHandler->getClientIp());

        if(!$this->Rating->findByIp($this->RequestHandler->getClientIp(),$id)) {
            if($this->Rating->save($data)) {
                $this->Session->setFlash(__('The Rating has been saved',true));
            } else {
                $this->Session->setFlash(__('The Rating could not be saved. Please, try again.',true));
            }
        } else {
            $this->Session->setFlash(__('You can rate only once',true));
        }

        if($this->RequestHandler->isAjax()) {
            $this->action = "rating_action";
        } else {
            $url = $this->get_article_url($seo_link);
            $this->redirect(array('action'=>$url),null,true);
        }
    }

    /**
     * sets information about article: categories, users, tags
     */
    private function get_article_data() {
        $categories = $this->Article->Category->find('list');
        $users = $this->Article->User->find('list');
        $tags = $this->Article->Tag->find('list');
        $this->set(compact('users','categories','tags'));;
    }

    /**
     * return normalized URL of article
     * @param <string> $seo_link
     * @return <string>
     */
    private function get_article_url($seo_link) {
        return $this->params['year'].'/'.$this->params['month'].'/'.$this->params['day'].'/'.$seo_link;
    }

    public function sidebox() {
        return $this->Article->best();
    }
}
?>